package com.blog.controller;

import cn.dev33.satoken.stp.SaTokenInfo;
import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.blog.dto.PasswordDTO;
import com.blog.dto.UserInfoDTO;
import com.blog.entity.Article;
import com.blog.entity.User;
import com.blog.service.ArticleService;
import com.blog.service.UserService;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.servlet.ModelAndView;


import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * code
 *
 * @author: garyme
 * @date: 2025/3/20 13:44
 * @description:
 */
@RestController
@RequestMapping("/api/user")
public class UserController {
    @Autowired
    private UserService userService;

    @Autowired
    private ArticleService articleService;

    /**
     * 获取当前用户信息
     */
    @GetMapping("/info")
    public ResponseEntity<User> getUserInfo() {
        // 检查用户是否已登录
        if (!StpUtil.isLogin()) {
            return ResponseEntity.status(401).body(null);
        }

        Long userId = StpUtil.getLoginIdAsLong();
        User user = userService.getById(userId);

        if (user != null) {
            // 不返回密码
            user.setPassword(null);
            return ResponseEntity.ok(user);
        } else {
            return ResponseEntity.notFound().build();
        }
    }

    /**
     * 更新用户信息
     */
    @PutMapping("/info")
    public ResponseEntity<Map<String, Object>> updateUserInfo(@RequestBody UserInfoDTO userInfoDTO) {
        // 检查用户是否已登录
        if (!StpUtil.isLogin()) {
            return ResponseEntity.status(401).body(null);
        }

        Long userId = StpUtil.getLoginIdAsLong();
        User user = userService.getById(userId);

        if (user == null) {
            return ResponseEntity.notFound().build();
        }

        // 更新用户信息
        if (userInfoDTO.getNickname() != null) {
            user.setNickname(userInfoDTO.getNickname());
        }
        if (userInfoDTO.getEmail() != null) {
            user.setEmail(userInfoDTO.getEmail());
        }
        if (userInfoDTO.getAvatar() != null) {
            user.setAvatar(userInfoDTO.getAvatar());
        }
        if (userInfoDTO.getBio() != null) {
            user.setBio(userInfoDTO.getBio());
        }

        userService.updateById(user);

        return ResponseEntity.ok(Map.of("message", "用户信息更新成功"));
    }

    /**
     * 修改密码
     */
    @PutMapping("/password")
    public ResponseEntity<Map<String, Object>> changePassword(@RequestBody PasswordDTO passwordDTO) {
        // 检查用户是否已登录
        if (!StpUtil.isLogin()) {
            return ResponseEntity.status(401).body(null);
        }

        Long userId = StpUtil.getLoginIdAsLong();
        User user = userService.getById(userId);

        if (user == null) {
            return ResponseEntity.notFound().build();
        }

        // 验证原密码
        String oldEncryptPassword = DigestUtils.md5DigestAsHex(passwordDTO.getOldPassword().getBytes());
        if (!user.getPassword().equals(oldEncryptPassword)) {
            return ResponseEntity.badRequest().body(Map.of("message", "原密码错误"));
        }

        // 更新密码
        String newEncryptPassword = DigestUtils.md5DigestAsHex(passwordDTO.getNewPassword().getBytes());
        user.setPassword(newEncryptPassword);
        userService.updateById(user);

        return ResponseEntity.ok(Map.of("message", "密码修改成功"));
    }

    /**
     * 获取用户安全信息
     */
    @GetMapping("/security")
    public ResponseEntity<Map<String, Object>> getSecurityInfo() {
        // 检查用户是否已登录
        if (!StpUtil.isLogin()) {
            return ResponseEntity.status(401).body(null);
        }

        // 获取当前用户ID
        Long userId = StpUtil.getLoginIdAsLong();

        // 获取会话信息
        SaTokenInfo tokenInfo = StpUtil.getTokenInfo();

        Map<String, Object> result = new HashMap<>();
        result.put("userId", userId);
        result.put("loginDevice", tokenInfo.getLoginDevice());
        result.put("tokenName", tokenInfo.getTokenName());
        result.put("tokenValue", tokenInfo.getTokenValue());

        // 添加登录时间（使用当前时间作为示例）
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        result.put("lastLoginTime", dateFormat.format(new Date()));

        // 尝试获取客户端IP
        try {
            ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            if (attributes != null) {
                HttpServletRequest request = attributes.getRequest();
                String ip = request.getRemoteAddr();
                result.put("lastLoginIp", ip);
            } else {
                result.put("lastLoginIp", "未知");
            }
        } catch (Exception e) {
            result.put("lastLoginIp", "未知");
        }

        return ResponseEntity.ok(result);
    }

    /**
     * 获取用户文章列表
     */
    @GetMapping("/articles")
    public ResponseEntity<Page<Article>> getUserArticles(
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "10") Integer pageSize,
            @RequestParam(required = false) Integer status) {
        // 检查用户是否已登录
        if (!StpUtil.isLogin()) {
            return ResponseEntity.status(401).body(null);
        }

        Long userId = StpUtil.getLoginIdAsLong();

        // 创建分页对象
        Page<Article> page = new Page<>(pageNum, pageSize);

        // 构建查询条件
        LambdaQueryWrapper<Article> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Article::getAuthorId, userId);
        if (status != null) {
            queryWrapper.eq(Article::getStatus, status);
        }
        queryWrapper.orderByDesc(Article::getCreateTime);

        // 执行查询
        Page<Article> articlePage = articleService.page(page, queryWrapper);

        return ResponseEntity.ok(articlePage);
    }
}
